from django.shortcuts import render, redirect
from django.http import HttpResponse
from ..forms import RegisterForm
from casedemo5.models import CaseDemoUser
from django.core.cache import cache
import uuid
# 这种函数表示每个模块的测试地址，如果这个地址是正常的，说明路径是没问题的
def index(request):
    context          = {}
    context['hello'] = 'Hello World! 这里是casedemo5'
    return render(request, 'casedemo5/index.html', context)

# 从调用service执行相关的操作,以登录为例
def casedemo5_login_index(request):
    # 判断缓存中是否存在username，如果存在，那么就跳转到登录成功页面
    if 'username' in request.session:
        return redirect('/casedemo5/checklogindemo1/')
    else:
        return render(request, 'casedemo5/login.html')

# 接收登录传输的数据
def casedemo5_checklogin_demo1(request):# 接受账户密码，如果符合数据库的要求，那么就可以直接的进行登录
    if 'username' in request.session and 'userid' in request.session:
        current_session = request.session.get('session_id')# 查看当前的session_id
        # 有缓存
        context = {}
        username= request.session['username']
        user_id = request.session.get('userid')
        context['message'] = f'Hello {username}! 登录成功'
        if not user_id:
            return redirect('login')
        # ✅ 从缓存中获取信息
        user_info = cache.get(f'user_info_{user_id}')
        valid_session=user_info['session_id']
        if valid_session == current_session:
            # ✅ session_id 匹配，登录成功
            context['user_info'] = user_info
            return render(request, 'casedemo5/message.html', context)
            #return render(request, 'casedemo5/message.html', context)
        else:
            # ✅ session_id 不匹配，登录失败
            context['message'] = '登录失败：会话已过期'
            return render(request, 'casedemo5/message.html', context)
    else:
        # 没有缓存
        context = {}
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            # 查询数据库中是否存在这个用户，且密码匹配
            user = CaseDemoUser.objects.get(username=username, password=password)
            if user:# 登录成功才会保存缓存
                session_id = str(uuid.uuid4())  # 生成一个唯一 session 标识符
                request.session['session_id'] = session_id
                # ✅ 登录成功，将用户信息和权限存入缓存
                cache_key = f'user_info_{user.useronlyID}'
                cache.set(cache_key, {
                    'username': user.username,
                    'email': user.email,
                    'session_id':session_id,
                }, timeout=60 * 60 * 2)  # 存2小时

                # ✅ 记录登录状态
                request.session['username'] = username
                request.session['userid'] = user.useronlyID
            context['message'] = f'Hello {user.username}! 登录成功'
        except CaseDemoUser.DoesNotExist:
            context['message'] = '登录失败：用户名或密码错误'
        return render(request, 'casedemo5/message.html', context)

# 写一个登出的函数
def casedemo5_logout(request):
    # 1. 获取用户名（从 session 中）
    username = request.session.get('username')
    userid= request.session.get('userid')
    # 2. 删除缓存（如果你有缓存用户信息）
    if userid:
        cache_key = f"user_info_{userid}"
        cache.delete(cache_key)
    # 3. 清空整个 session（推荐）
    request.session.flush()
    return redirect('/casedemo5/login/')

def casedemo5_register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'casedemo5/success.html')
    else:
        form = RegisterForm()
    return render(request, 'casedemo5/register.html', {'form': form})